package com.stack.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

/**
 * @author llz
 * @date 2023/11/16 10:53
 * @description
 */
@Slf4j
public final class AESUtil {

    private static final String ENCODING = "UTF-8";
    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_CBC = "AES/CBC/PKCS7Padding";
    private static final String ALGORITHM_ECB = "AES/ECB/PKCS7Padding";
    private static final String DEFAULT_ALGORITHM = "AES/ECB/PKCS5Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        try {
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            // 此类提供加密的强随机数生成器 (RNG)，该实现在windows上每次生成的key都相同，但是在部分linux或solaris系统上则不同。
            // SecureRandom random = new SecureRandom(key.getBytes());
            // 指定算法名称，不同的系统上生成的key是相同的。
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            //AES 要求密钥长度为 128
            kg.init(128, random);
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            log.info("生成加密秘钥异常！");
        }
        return null;
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param key     加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key) {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM);
            byte[] byteContent = content.getBytes(ENCODING);
            // 初始化为加密模式的密码器
            SecretKeySpec secretKey = getSecretKey(key);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //通过Base64转码返回
            return new String(Base64.getEncoder().encode(result));
        } catch (Exception ex) {
            log.error("加密失败", ex);
        }

        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(String content, String key) {
        try {
            if (StringUtils.isBlank(content)){
                return content;
            }
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            //执行操作
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content.getBytes(ENCODING)));
            return new String(result, ENCODING);
        } catch (Exception ex) {
            log.error("解密失败", ex);
        }

        return null;
    }

    /**
     * 加密
     *
     * @param content
     * @param key
     * @return
     */
    public static String encryptCBC(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), KEY_ALGORITHM);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(subBytes(key.getBytes(ENCODING)));
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
            byte[] result = cipher.doFinal(content.getBytes(ENCODING));
            return new String(Base64.getEncoder().encode(result));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @param key
     * @return
     */
    public static String decryptCBC(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), KEY_ALGORITHM);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(subBytes(key.getBytes(ENCODING)));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
            return new String(cipher.doFinal(Base64.getDecoder().decode(content.getBytes(ENCODING))), ENCODING);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return StringUtils.EMPTY;
    }

    /**
     * AES加密
     * @param source	源字符串
     * @param key	密钥
     * @return	加密后的密文
     * @throws Exception
     */
    public static String encryptECB(String source, String key){
        try {
            byte[] sourceBytes = source.getBytes(ENCODING);
            byte[] keyBytes = key.getBytes(ENCODING);
            Cipher cipher = Cipher.getInstance(ALGORITHM_ECB);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM));
            byte[] decrypted = cipher.doFinal(sourceBytes);
            return new String(Base64.getEncoder().encode(decrypted));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密
     * @param base64Data
     * @return
     * @throws Exception
     */
    public static String decryptECB(String base64Data, String hexKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(hexKey.getBytes(), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_ECB);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(Base64.getDecoder().decode(base64Data.getBytes(ENCODING))), ENCODING);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 从一个byte[]数组中截取一部分
     * @param src
     * @return
     */
    public static byte[] subBytes(byte[] src) {
        if (src.length < 16) {
            throw new RuntimeException("无法从Key中获取偏移量!");
        }
        byte[] bs = new byte[16];
        for (int i=0; i<16; i++){
            bs[i] = src[i];
        }
        return bs;
    }

    public static void main(String[] args) {
        String encrypt = encrypt("421125196703121319", "46CC1C4D1C474A8029EAB203541510");
        System.out.println(encrypt);
    }

}
